package com.ddyx.common.framework.filter;

import com.ddyx.common.framework.aop.annotation.LoginRequired;
import com.ddyx.common.base.enums.ApiResultType;
import com.ddyx.common.utils.io.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限拦截器
 * @author agula
 * @date 2019-07-12 15:27
 */
@Configuration
public class AuthorityInterceptor extends HandlerInterceptorAdapter {

//	@Resource
//	private IUserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
		// 这一步必须的
		if (!(handler instanceof HandlerMethod)) {
			return super.preHandle(request, response, handler);
		}
		HandlerMethod hm = (HandlerMethod) handler;

		// 如果没有注解 LoginRequired，直接通过
		if (!hm.getMethod().isAnnotationPresent(LoginRequired.class) && !hm.getBeanType().isAnnotationPresent(LoginRequired.class)) {
			return super.preHandle(request, response, handler);
		}

		/**
		 * 除业务对象数据，其他信息放在header中
		 */
		String token = request.getHeader("token");
		if (StringUtil.isEmpty(token)) {
			writeJsResponse(response, ApiResultType.PARAMER_ERROR);
			return false;
		}
		/*User user = userService.getUserByToken(token);
		if (user == null){
			writeJsResponse(response, ApiResultType.TOKEN_ERROR);
			return false;
		}*/

		// 设置用户到session 接口内部使用
		//request.getSession().setAttribute(UserType.USER_SESSION, user);
		// 资源前缀
		request.setAttribute("ctx", request.getContextPath());

		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		//资源前缀
		request.setAttribute("ctx", request.getContextPath());
		super.postHandle(request, response, handler, modelAndView);
	}

	// handler结束后清除session
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.invalidate();
		}
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		afterConcurrentHandlingStarted(request, response, handler);
	}

	private void writeJsResponse(HttpServletResponse response, ApiResultType art) {
		try {
			response.setHeader("Content-Type", "application/json;charset=UTF-8");
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("code", art.getCode());
			resultMap.put("data", new JSONObject());
			resultMap.put("message", art.getMessage());
			response.getWriter().write(JSONObject.fromObject(resultMap).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
